package com.example.demo.order.config;

import com.example.demo.util.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.*;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Order(-1)
@Slf4j
public class EnvironmentDecryptPostProcessor implements EnvironmentPostProcessor {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        String property = environment.getProperty("encryptKey");
        log.info("====== property:{}", property);
        AESUtil aesUtil = new AESUtil(property);

        Map<String, Object> decyptMap = new HashMap<>();
        MutablePropertySources propertySources = environment.getPropertySources();
        for (PropertySource<?> propertySource : propertySources) {
            if (propertySource instanceof EnumerablePropertySource<?> ps) {
                String[] propertyNames = ps.getPropertyNames();
                for (String propertyName : propertyNames) {
                    String value = environment.getProperty(propertyName);
                    log.info("====== propertyName:{}", propertyName);
                    if (StringUtils.startsWith(value,AESUtil.CONFIG_PREFIX)) {
                        String decrypt = aesUtil.decrypt(value);
                        decyptMap.put(propertyName,decrypt);
                    }
                }
            }
        }
        propertySources.addFirst(new MapPropertySource("decrypt", decyptMap));
    }
}
